package com.atguigu.gmall.common.config.thread;

import com.atguigu.gmall.common.config.thread.properties.AppThreadProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@EnableConfigurationProperties(AppThreadProperties.class)
@Configuration
public class AppThreadPoolAutoConfiguration {

    @Bean
    public ThreadPoolExecutor coreExecutor(AppThreadProperties appThreadProperties) {
        return new ThreadPoolExecutor(appThreadProperties.getCorePoolSize(), //核心线程数
                appThreadProperties.getMaximumPoolSize(), //最大线程数
                appThreadProperties.getKeepAliveTime(), // 弹性线程消失时间
                TimeUnit.MINUTES, //时间单位
                new LinkedBlockingQueue<>(appThreadProperties.getWorkQueueSize()), //阻塞队列
                new ThreadFactory() {
                    int i = 1;
                    @Override
                    public Thread newThread(Runnable r) {

                        Thread thread = new Thread(r);
                        thread.setName("核心线程[" + i++ + "]");//设置县城名字
                        thread.setPriority(10);//设置优先级
                        return thread;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }
}
